//题目:
// 给你二叉树的根节点 root ，返回其节点值的 锯齿形层序遍历 。
//（即先从左往右，再从右往左进行下一层遍历，以此类推，层与层之间交替进行）
#include<iostream>
#include<stack>
#include<vector>

using namespace std;
//代码:
//Definition for a binary tree node.
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution 
{
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) 
    {
        stack<TreeNode*> st1,st2;
        vector<vector<int>> ret;
        if(root!=nullptr)st1.push(root);
        while(!st1.empty() || !st2.empty())
        {
            vector<int> v;
            //st1:从左往右出栈，子节点先左再右； st2:从右往左出栈，子节点先右再左
            if(!st1.empty())
            {
                while(!st1.empty())
                {
                    TreeNode* node=st1.top();
                    st1.pop();
                    if(node->left)st2.push(node->left);
                    if(node->right)st2.push(node->right);
                    v.push_back(node->val);
                }
            }
            else
            {
                while(!st2.empty())
                {
                    TreeNode* node=st2.top();
                    st2.pop();
                    if(node->right)st1.push(node->right);
                    if(node->left)st1.push(node->left);
                    v.push_back(node->val);
                }
            }
            ret.push_back(v);
        }
        return ret;
    }
};